'''
tickets1, webapp to insert barcode to SVG templates from database.
Copyright (C) 2018 Rodrigo Garcia

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
'''
import os

from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist

from tickets1.settings import *

from django.http import HttpResponse, HttpResponseRedirect

from .models import Tienda, Precio, Ticket, GrupoTickets
from .utils import generarCodioDeBarras, contenidoArchivo, escribirArchivo, \
     introducirBarcodeSVGEnOtroSVG, reemplazarEtiquetasEnSVG,\
     dicEtiquetasParaSVG, exportarSVGsEnPdfs, empaquetarPdfsGenerados, \
     unirGrupoDePdfs
from .utils import STATIC_SVGS, STATIC_SVG_TEMPLATES_FOLDER, \
     STATIC_GENERATED_SVGS

def menuView(request):
    if not request.user.is_superuser:
        return HttpResponseRedirect('/admin/')
    return TemplateResponse(request, 'registro/menu.html', {})

class TiendaList(ListView):
    model = Tienda

class TicketList(ListView):
    model = Ticket

class PrecioList(ListView):
    model = Precio
    
class GrupoTicketsList(ListView):
    model = GrupoTickets

class TiendaDetailView(DetailView):
    model = Tienda
    
    def get_context_date(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

class PrecioDetailView(DetailView):
    model = Precio
    
class GrupoTicketsDetailView(DetailView):
    model = GrupoTickets

class TicketDetailView(DetailView):
    model = Ticket
    def get_context_date(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

class TiendaCreateView(CreateView):
    model = Tienda
    fields = ['nombre', 'departamento', 'direccion', 'nit', 
               'factura_nro_inicio',  'factura_nro_final', 'template_svg']

class PrecioCreateView(CreateView):
    model = Precio
    fields = ['costo_numeral', 'costo_literal']
    
class GrupoTicketsCreateView(CreateView):
    model = GrupoTickets

    fields = ['tienda', 'nro_tickets', 'cod_control_inicio',
                  'template_svg', 'desc_producto', 'precio']
    
class TicketCreateView(CreateView):
    model = Ticket
    fields = ['tienda', 'nro_factura', 'svg_generado', 'costo',
                  'codigo_de_barras', 'template_svg']

class TiendaUpdateView(UpdateView):
    model = Tienda
    fields = ['nombre', 'departamento', 'direccion', 'nit', 
              'template_svg']

class PrecioUpdateView(UpdateView):
    model = Precio
    fields = ['costo_numeral', 'costo_literal']
    
class GrupoTicketsUpdateView(UpdateView):
    template_name = 'registro/grupotickets_update_form.html'
    model = GrupoTickets
    fields = ['tienda', 'precio','cod_control_inicio',
                  'template_svg', 'desc_producto']
        
class TicketUpdateView(UpdateView):
    model = Ticket
    fields = ['tienda', 'nro_factura', 'svg_generado', 'costo',
                  'codigo_de_barras', 'template_svg']

class GrupoTicketsGenerarPdfIndividual(DetailView):
    model = GrupoTickets
    
    def get(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            return HttpResponse("No autorizado")
        self.object = self.get_object()
        self.object.GenerarPdf()
        return HttpResponseRedirect(self.object.get_absolute_url())
        
# @funcion que no se usa        
class TicketGenerarSVG(DetailView):
    model = Ticket

    def get(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            return HttpResponse('No Autorizado')
        self.object = self.get_object()
        generado = generarCodioDeBarras(self.object.codigo_de_barras, STATIC_GENERATED_SVGS)
        svg_generado = introducirBarcodeSVGEnOtroSVG(generado,
                                             STATIC_SVG_TEMPLATES_FOLDER +
                                                 self.object.template_svg)
        # extrayendo datos para reemplazar en la plantilla SVG
        dict = dicEtiquetasParaSVG(self.object)
        reemplazarEtiquetasEnSVG(dict, svg_generado)
        
        self.object.svg_generado = svg_generado
        self.object.save()

        return HttpResponse()
        return HttpResponseRedirect('/tickets/'+str(self.object.id)+'/')
    #return HttpResponse(contenidoArchivo(STATIC_GENERATED_SVGS + self.object.codigo_de_barras + '.svg'))

# @funcion que no se usa
def ticketGenerarPdfs(request):
    ''' Funcion para crear pdfs para varios objetos '''
    if not request.user.is_superuser:
        return HttpResponse('No autorizado')

    if request.method== "POST":
        print (str(request.POST))
        tickets = []
        for id in request.POST.getlist('checkboxes'):
            try:
                ticket = Ticket.objects.get(id=id)
                print (ticket)
                generado = generarCodioDeBarras(ticket.codigo_de_barras, STATIC_GENERATED_SVGS)
                svg_generado = introducirBarcodeSVGEnOtroSVG(generado,
                                                             STATIC_SVG_TEMPLATES_FOLDER +
                                                                 ticket.template_svg)
                dict = dicEtiquetasParaSVG(ticket)
                reemplazarEtiquetasEnSVG(dict, svg_generado)
                if svg_generado is not None:
                    ticket.svg_generado = svg_generado
                    ticket.save()
                    tickets.append(ticket)
                
            except ObjectDoesNotExist as e:
                print (e)
        s = exportarSVGsEnPdfs(tickets)
        print('generando PDFs:'+str(s))
        # empaquetando los creados en un .tar.gz
        #tarball = empaquetarPdfsGenerados(s)
        #print(tarball)
        #return HttpResponse('<html> <body>Listo, se han generado '+str(len(s))+' pdfs <br>'+str(s)+'-->'+tarball+'<br><a href="/{}">Descargar</a>'.format(tarball)+'</body></html>')

        # uniendo todos los archivos generados en un solo pdf
        pdf = unirGrupoDePdfs(s)
        print(pdf)

        return HttpResponse('<html> <body>Listo, se generado <b>'+str(len(s))+'</b> tickets <br>'+str(s)+'-->'+pdf+'<br><a href="/{}">Descargar</a>'.format(pdf)+'</body></html>')
    
# TODO: corregir esta funcion (realmente hace falta?)
class TicketGenerarPDF(DetailView):
    model = Ticket

    def get(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            return HttpResponse('No autorizado')
        self.object = self.get_object()
        
        if self.object.svg_generado == '-':
            generado = generarCodioDeBarras(self.object.codigo_de_barras, STATIC_GENERATED_SVGS)
            svg_generado = introducirBarcodeSVGEnOtroSVG(generado,
                                             STATIC_SVG_TEMPLATES_FOLDER +
                                                 self.object.template_svg)
            self.object.svg_generado = svg_generado
            dict = dicEtiquetasParaSVG(self.object)
            reemplazarEtiquetasEnSVG(dict, svg_generado)
            self.object.save()
            
            # generando el PDF
        print ("generando PDF:"+str(exportarSVGsEnPdfs([self.object])))
        return HttpResponseRedirect('/tickets/'+str(self.object.id)+'/')
    
'''Para insertar el svg generado de pybarcode
== Para el barcode volcado

1) ajustar la distancia del texto para que este mas cerca del codigo de barras

   ean.default_writer_options['text_distance']=3.0

Para reducir el cuadro blanco

   ean.default_writer_options['quiet_zone'] = 0.1


2) Como pybarcode genera un svg se puede introducir ese SVG en:

TODO: poner donde

3) En la etiqueta <g agregar:

transform="matrix(0,1.2379845,-0.4466589,0,271.09792,1.579233)"

== Para el barcode pequenyo 

4) 
en la etiqueta '<g' agregar:
transform="matrix(0.63169051,0,0,0.33599068,326.07055,116.87741)"
'''    
